package com.iciot.web.controller;

import com.iciot.domain.User;
import com.iciot.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

@WebServlet("/findAllServlet")
public class findAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 调用 UserServiceImpl 的 findAll() 方法获取所有用户
        UserServiceImpl userService = new UserServiceImpl();
        try {
            ArrayList<User> users = userService.getAll();

            // 设置响应内容类型为 HTML
            resp.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = resp.getWriter();

            // 构建 HTML 表格
            writer.write("<html>");
            writer.write("<head><title>用户列表</title></head>");
            writer.write("<body>");
            writer.write("<div align=\"center\">");
            writer.write("<h2>所有用户列表</h2>");
            writer.write("<table  border=\"1\" width=\"300\" height=\"150\" align=\"center\" cellspacing= \"0\" cellpadding=\"20\"");
            writer.write("<tr><th>ID</th><th>用户名</th><th>密码</th></tr>");

            // 遍历用户列表，将每个用户的信息写入表格
            for (User user : users) {
                writer.write("<tr>");
                writer.write("<td>" + user.getUid() + "</td>");
                writer.write("<td>" + user.getUname() + "</td>");
                writer.write("<td>" + user.getUpwd() + "</td>");
                writer.write("</tr>");
            }

            writer.write("</table>");
            writer.write("</div>");
            writer.write("</body>");
            writer.write("</html>");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
